//
//  SearchBarView.m
//
//
//  Created by gynjobs on 2017/8/14.
//  Copyright © 2017年 gynjobs. All rights reserved.
//

#import "SearchBarView.h"

@interface SearchBarView ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic,strong) UIView *searchBgView;
@end

@implementation SearchBarView

-(instancetype) init{
    
    if(self = [super init]){
        
        self.backgroundColor = [UIColor whiteColor];
        
        self.aSearchBar = [[UISearchBar alloc] init];
        [self barStyleConfig];
        
        self.aTableView = [[UITableView alloc] init];
        self.aTableView.backgroundColor = [UIColor colorWithString:UI_COLOR_MAIN_BG_1];
        self.aTableView.dataSource = self;
        self.aTableView.delegate = self;
        
        self.dataSource = nil;
        self.contentTableView = nil;
        self.tableArray = [[NSMutableArray alloc] init];
        
        [self addSubview:self.searchBgView];
        [self addSubview:self.aSearchBar];
        [self updateConstraintsIfNeeded];
    }
    
    return self;
}


- (void)barStyleConfig{
    self.aSearchBar.placeholder = @"搜索城市";
    self.aSearchBar.showsCancelButton = NO;
    //    aSearchBar.returnKeyType = UIReturnKeyDone;
    self.aSearchBar.delegate = self;
    self.aSearchBar.backgroundColor = [UIColor whiteColor];
    for (UIView *view in self.aSearchBar.subviews.firstObject.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
        }else{
            view.layer.cornerRadius = 5;
            view.layer.masksToBounds = YES;
        }
    }
    UIImage *bgimage = [self getImageWithColor:[UIColor colorWithString:@"#eaeaea"] andHeight:SERCH_BAR_HEIGHT];
    [self.aSearchBar setSearchFieldBackgroundImage:bgimage forState:UIControlStateNormal];
    
}


-(void)start{
    
    //    UIView* superView = [self superview];
    //    [superView addSubview:aTableView];
    //    [aTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    //
    //        make.left.equalTo(superView.mas_left);
    //        make.right.equalTo(superView.mas_right);
    //        make.top.equalTo(self.mas_bottom);
    //        make.bottom.equalTo(superView.mas_bottom);
    //
    //    }];
    
}

-(void)updateConstraints{
    
    [super updateConstraints];
    
    [self.aSearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(LEFT_RIGHT_SPACE - 8);
        make.right.equalTo(self.mas_right).with.offset(-LEFT_RIGHT_SPACE + 8);
        make.centerY.equalTo(self.mas_centerY);
        make.height.mas_equalTo(SERCH_BAR_HEIGHT);
    }];
    
}

#pragma mark -
#pragma mark tableview datasouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.tableArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString * cellId = @"search.cell.id";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if(!cell){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    CityInfo * city = [self.tableArray objectAtIndex:[indexPath row]];
    cell.textLabel.text = city.zone_name;
    
    return cell;
}


#pragma mark -

#pragma mark tableview delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CityInfo * city = [self.tableArray objectAtIndex:[indexPath row]];
    
    if(self.searchDelegate && [self.searchDelegate respondsToSelector:@selector(citySearchBar:)]){
        
        [self.searchDelegate citySearchBar:city];
    }
}



#pragma mark -
#pragma mark search bar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)mySearchBar{
    GYNLog(@"任务编辑文本");
    
    [self.tableArray removeAllObjects];
    [self.aTableView reloadData];
    
    self.contentTableView.hidden = YES;
    mySearchBar.showsCancelButton = YES;
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO ;
    
    [searchBar resignFirstResponder];
    self.contentTableView.hidden = NO;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    GYNLog(@"编辑完成");
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [self searchAction:searchBar.text];
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    GYNLog(@"点击完成");
    searchBar.showsCancelButton = NO ;
    [searchBar resignFirstResponder];
    self.contentTableView.hidden = NO;
    
}


-(void)searchAction:(NSString*)str{
    
    if(!self.dataSource){
        
        return;
    }
    
    if(!str || [str length] == 0){
        
        [self.tableArray removeAllObjects];
        [self.aTableView reloadData];
        return;
    }
    
    NSMutableArray * array = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < [self.dataSource count]; i++) {
        
        NSArray * subs = [[self.dataSource objectAtIndex:i] valueForKey:@"subs"];
        for (NSInteger j = 0; j < [subs count]; j++) {
            
            CityInfo * city = [subs objectAtIndex:j];
            
            if([city.zone_name hasPrefix:str]){
                
                [array addObject:city];
            }
            
        }
        
        if([array count] > 0){
            
            break;
        }
    }
    
    self.tableArray = array;
    [self.aTableView reloadData];
    
}

- (UIImage*)getImageWithColor:(UIColor*)color andHeight:(CGFloat)height{
    CGRect rect = CGRectMake(0, 0, 1, height);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
